module planegame{

    export class Plane extends egret.Sprite {

        public bullet:Bullet;
        public canHit:boolean;

        private fireTimer: egret.Timer;

        // 是否在使用
        public used: boolean;

        // 子弹数组
        public bulletArray: Array<BulletModule>;

        public constructor(resName:string) {
            super();

            this.bulletArray = new Array<BulletModule>();

            let result = new egret.Bitmap();
            let texture: egret.Texture = RES.getRes(resName);
            result.texture = texture;
            this.width = texture.textureWidth;
            this.height = texture.textureHeight;

            this.canHit = true;

            this.addChild(result);

            let fireTimer:egret.Timer = new egret.Timer(100, 0);
            this.fireTimer = fireTimer;

            this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
        }

        public setBullet(resName:string, bulletType:number, game:Game) {
            this.bullet = BulletFactory.createBullet(resName, bulletType, game);
            this.addChild(this.bullet);
        }

        public fire() {
            //this.parent.addChild(this.bullet);
            this.bullet.fire();
        }

        private onTimeUpdate():void{
            //egret.log("plane onTimeUpdate");
            this.fire();
        }

        private onAddToStage(event: egret.Event) {
            this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
            this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.end, this);

            // timer
            this.fireTimer.addEventListener(egret.TimerEvent.TIMER, this.onTimeUpdate, this);
            this.fireTimer.start();
        }

        public setTimerDelay(delay:number) {
            this.fireTimer.delay = delay;
        }

        // recycle
        public end() {
            this.removeEventListener(egret.Event.REMOVED_FROM_STAGE, this.end, this);
            this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);

            
            // timer
            if(this.fireTimer.running) {
                this.fireTimer.stop();
            }

            if(this.fireTimer.hasEventListener(egret.TimerEvent.TIMER)) {
                this.fireTimer.removeEventListener(egret.TimerEvent.TIMER, this.onTimeUpdate, this);
            }

            this.used = false;

            // 清除子弹
            //this.bullet.clearAllBullet();
            
        }
    }
}